package server.communication.ClientMessages;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import server.communication.Client;
import server.communication.MessageProcessor;

public class ExecuteCommandMessageThread extends ClientMessageThread{

	private Socket root;
	private BufferedReader rootIn;
	private PrintWriter rootOut;
	private String command;
	public ExecuteCommandMessageThread(Client parent, Socket root, String command) throws Exception
	{
		super(parent);
		this.root = root;
		this.command = command;
		rootIn = new BufferedReader(new InputStreamReader(root.getInputStream()));
		rootOut = new PrintWriter(root.getOutputStream(), true);
	}
	
	private void transferToRoot()
	{
		try
		{
			String input = in.readLine();
			System.out.println(input);
			rootOut.println(input);
			while ((input = in.readLine())!=null && !input.equals("file:finished"))
			{
				rootOut.println(input);
			}
			System.out.println("file downloading finished");
			rootOut.println("file:finished");
		}
		catch(Exception e)
		{
			System.out.println("User "+parent.getHostName()+" didn't answer for exec request");
			rootOut.println("done:null");
		}
	}
	
	@Override
	public void run()
	{
		String input = null;
		out.println(MessageProcessor.executeCommandRequest(command));
		if (command.startsWith("download "))
		{
			transferToRoot();
		}
		else
		{
			while(true){
				try
				{
					input = in.readLine();
					if (input.startsWith("done"))
					{
						rootOut.println(input);
						break;
					}
					else
						parent.getMessageProcessor().process(input);
				}
				catch (Exception e ){rootOut.println( "done:exception");}
			}
		}
		parent.removeMessageThread(this);
		parent.resumeMessages();
	}
}
